package org.ahuanlien.crm.service.impl;

import org.ahuanlien.crm.domain.Permission;
import org.ahuanlien.crm.mapper.PermissionMapper;
import org.ahuanlien.crm.query.QueryObject;
import org.ahuanlien.crm.service.IPermissionService;
import org.ahuanlien.crm.util.PageResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService {

	@Autowired
	private PermissionMapper permissionMapper;

	@Autowired
	private RequestMappingHandlerMapping rmhm;


	public void reload() {
		//获取到所有数据库已存在的权限表达式
		List<String> resources = permissionMapper.getAllResource();
		//获取到所有贴了RequestMapping注解的方法
		Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();
		//获取到对应的方法对象
		Collection<HandlerMethod> methods = handlerMethods.values();
		//遍历每一个方法对象
		for (HandlerMethod method : methods) {
			//判断该方法上有无RequiresPermissions注解
			RequiresPermissions annotation = method.getMethodAnnotation(RequiresPermissions.class);
			if (annotation != null) {
				//注解上有两个value值,一个为权限表达式,一个为该权限的名称
				String[] value = annotation.value();
				if(!resources.contains(value[0])){
					Permission permission = new Permission();
					permission.setName(value[1]);
					permission.setResource(value[0]);
					permissionMapper.insert(permission);
				}
			}

		}
	}

	public List<String> getResourceByEmployeeId(Long id) {
		return permissionMapper.getResourceByEmployeeId(id);
	}


	public List<Permission> selectAll() {
		return permissionMapper.selectAll();
	}

	public List<Permission> selectPermissionByRoleId(Long id) {
		return permissionMapper.selectPermissionByRoleId(id);
	}

	public PageResult query(QueryObject qo) {
		int count = permissionMapper.queryForCount(qo);
		if (count == 0) {
			return new PageResult(count, Collections.EMPTY_LIST);
		}
		List<Permission> result = permissionMapper.queryForList(qo);
		return new PageResult(count, result);
	}

	public int insert(Permission record) {
		return permissionMapper.insert(record);
	}


}
